<?php
/**************************************************************************
	ESAM (EVE to SMF API Module)
	Copyright (C) 2009  Clinton Weiss

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

if (!defined('SMF')) die('SMF has not been loaded!');

db_query("
  CREATE TABLE IF NOT EXISTS {$db_prefix}esam_api (
		ID_MEMBER				INT(20) NOT NULL,
		USER_ID					VARCHAR(8),
		API_KEY					VARCHAR(64),
		PRIMARY KEY			(ID_MEMBER)
	)
", __FILE__, __LINE__);

db_query("
  CREATE TABLE IF NOT EXISTS {$db_prefix}esam_rules (
		ID_RULE					INT(20) NOT NULL AUTO_INCREMENT,
		TYPE						VARCHAR(1),  
		ROLE						VARCHAR(16), 
		ROLE_ID					INT(32),     
		GROUP_ID				INT(11),     
		PRIMARY KEY			(ID_RULE)
	)
", __FILE__, __LINE__);
/*
 *
 * Comments brought down here since SMF assumes comments in queries
 * are a hacking attempt!
		TYPE						VARCHAR(1),  -- C - corp, A - Alliance, P - Pilot
		ROLE						VARCHAR(16), -- usually blank, but can be 'roleDirector'
		ROLE_ID					INT(32),     -- typically the corp/pilot/alliance id
		GROUP_ID				INT(11),     -- the member group
 */

// Skills are now tied to the rules.  We'll delete any existing
// skill rules and then add the columns.
db_query("delete from {$db_prefix}esam_rules where TYPE = 'S'", __FILE__, __LINE__);
addColumnIfNotExists("{$db_prefix}esam_rules", "SKILL_ID", "INT");
addColumnIfNotExists("{$db_prefix}esam_rules", "SKILL_LVL", "TINYINT");

db_query("
  CREATE TABLE IF NOT EXISTS {$db_prefix}esam_settings (
		ID_SETTING			INT(20) NOT NULL AUTO_INCREMENT,
		ID_MEMBER				INT(11),
		NAME						VARCHAR(32),
		VALUE						VARCHAR(32),
		PRIMARY KEY			(ID_SETTING)
	)
", __FILE__, __LINE__);

function addColumnIfNotExists($tableName, $columnName, $columnType)
{
  global $db_prefix, $db_name;
  $request = db_query("
    SELECT count(*) count
    FROM information_schema.COLUMNS
    WHERE
      COLUMN_NAME='$columnName' and
      TABLE_NAME='$tableName' and
      TABLE_SCHEMA='{$db_name}'
  ", __FILE__, __LINE__);
  $result = array();
  while($row = mysql_fetch_assoc($request))
  {
     $result[] = $row;
  }
  mysql_free_result($request);

  if ($result[0]['count'] == 0)
  {
    db_query("alter table $tableName add column $columnName $columnType", __FILE__, __LINE__);
  }
}
?>
